/**
 * 引入包
 * 创建路由对象（一定要指定路由模式），设置路由规则，并且导出
 */
import { createRouter, createWebHashHistory } from 'vue-router'
import { useUserStore } from '@/store/user'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
NProgress.configure({ showSpinner: false })

// Vite必须写完整路径
import Layout from '../views/Layout/index.vue'
import Login from '../views/Login/index.vue'
import Home from '@/views/Home/index.vue'
import Category from '@/views/Category/index.vue'
import Cart from '@/views/Cart/index.vue'
import My from '@/views/My/index.vue'
import NotFound from '../views/NotFound/index.vue'

const GoodsDetail = () => import('@/views/GoodsDetail/index.vue')

const router = createRouter({
  history: createWebHashHistory(), //  路由模式，一定要有
  routes: [
    {
      path: '/',
      redirect: '/home',
      component: Layout,
      children: [
        {
          path: 'home',
          component: Home
        },
        {
          path: 'category',
          component: Category
        },
        {
          path: 'cart',
          component: Cart
        },
        {
          path: 'my',
          component: My,
          meta: {
            needAuth: true
          }
        }
      ]
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/detail',
      component: GoodsDetail
    },
    {
      path: '/order',
      component: () => import('@/views/Order/index.vue'),
      meta: {
        needAuth: true
      }
    },
    {
      path: '/:pathMatch(.*)',
      component: NotFound
    }
  ]
})

router.beforeEach((to, from) => {
  NProgress.start()

  if (to.meta.needAuth) {
    // 进入到权限判断
    const store = useUserStore()
    if (store.token) {
      return true
    } else {
      return `/login?redirect=${to.fullPath}`
    }
  } else {
    return true
  }
})

router.afterEach((to, from) => {
  NProgress.done()
})

export default router
